package com.lxj.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lxj.common.Result;
import com.lxj.domain.SysRole;
import com.lxj.dto.SysRoleDto;
import com.lxj.mapper.SysRoleMapper;
import com.lxj.service.RoleService;
import com.lxj.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lxj
 * @date 2021/6/18 14:13
 * @Description:角色的服务
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private SysRoleMapper mapper;
    /**
     * 新增角色
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result addRole(SysRoleDto dto) {
        SysRole sysRole = new SysRole();
        BeanUtil.copyProperties(dto,sysRole);
        mapper.insert(sysRole);
        return new Result();
    }
    /**
     * 根据id删除角色
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result deleteRoleById(Integer id) {
        mapper.deleteByPrimaryKey(id);
        return new Result();
    }
    /**
     * 批量删除角色
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public Result batchDelete(Integer[] ids) {
        mapper.batchDelete(ids);
        return new Result();
    }
    /**
     * 修改角色
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public Result updateRole(SysRoleDto dto) {
        SysRole sysRole = new SysRole();
        BeanUtil.copyProperties(dto,sysRole);
        mapper.updateByPrimaryKeySelective(sysRole);
        return new Result();
    }
    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public PageInfo<SysRole> selectPage(SysRoleDto dto) {
        Page<Object> pageData = PageHelper.startPage(dto.getPage(), dto.getLimit());
        List<SysRole> data = mapper.selectByPage(dto);
        return new PageInfo<SysRole>(pageData.getTotal(), data);
    }

    /**
     * 使用用户的id查询当前用户的角色的id集合
     * @param userId
     * @return
     */
    @Override
    public List<Integer> getUserRoleIds(Integer userId) {
        return mapper.selectByUserId(userId);
    }

    /**
     * 查询所有的角色数据
     * @return
     */
    @Override
    public List<SysRole> selectAllRoles() {
        return mapper.selectAllRoles();
    }

    /**
     * 给用户分配角色数据
     * @param userId
     * @param roleIds
     */
    @Override
    @Transactional
    public void assign(Integer userId, Integer[] roleIds) {
        //删除旧值
        mapper.deleteByUserId(userId);
        //创建新值
        mapper.insertNewRoles(userId, roleIds);
    }

    /**
     * 通过用户的id查询用户的角色
     * @param id
     * @return
     */
    @Override
    public List<SysRole> findByUserId(Integer id) {
        return mapper.selectRoleByUserId(id);
    }
}
